// 全局路由守卫
import config  from '@/config/config';
import data from '@/pages.json';
import useMenuStore from '@/stores/modules/menu';
import router from '@/router';
export default function RouterGuard() {
	// 监听浏览器输入框直接输入路径
	window.addEventListener('popstate', event => {
		let url = location.hash.replace('#', '');
		let newUrl = url.split('?');
		const store = useMenuStore();
		if (!uni.getStorageSync('userInfo').token) {
			uni.redirectTo({
				url: config.loginPage
			});
		} else {
			if (newUrl[0] === config.loginPage || newUrl[0] === '/pages/error/error') {
				uni.redirectTo({
					url: '/pages/error/error'
				});
				store.userInfo.defaultAct = '-1';
				store.userInfo.pageTitle = '错误页';
			} else if (newUrl[0] === '/pages/index/index') {
				store.userInfo.defaultAct = '0';
				store.userInfo.pageTitle = '首页'
			} else {
				let hashUrl = data.pages.filter(item => {
					return newUrl[0] == '/' + item.path;
				});
				if (!hashUrl.length) {
					//防止部分菜单跳转空白页
					uni.redirectTo({
						url: '/pages/error/error'
					});
					store.userInfo.defaultAct = '-1';
					store.userInfo.pageTitle = '错误页'
					return;
				}
				// 过滤权限
					let permitUrl = store.userInfo.permitUrl;
					if (permitUrl.includes(newUrl[0])) {
						for (let i in store.userInfo.flattenTree) {
							if (store.userInfo.flattenTree[i].path === newUrl[0]) {
								store.userInfo.defaultAct = store.userInfo.flattenTree[i].index;
								store.userInfo.pageTitle = store.userInfo.flattenTree[i].name;
								break
							}
						}
					} else {
						//无权限 跳转error
						store.userInfo.defaultAct = '-1';
						store.userInfo.pageTitle = '错误页'
						uni.redirectTo({
							url: '/pages/error/error'
						});

					}
				
			}
		}
	});
}
